import 'package:elephant_fish/TRTCChatSalonDemo/model/TRTCChatSalonDef.dart';
import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/room_request.dart';
import 'package:elephant_fish/model/voice_room_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/widget/voice_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class IndexVoiceHomePage extends StatefulWidget {
  final int categoryName;

  const IndexVoiceHomePage({Key key, this.categoryName}) : super(key: key);

  @override
  _IndexVoiceHomePageState createState() => _IndexVoiceHomePageState();
}

class _IndexVoiceHomePageState extends State<IndexVoiceHomePage> {

  List<VoiceRoomEntity> roomList = [];
  int pageIndex = 1;
  bool _loading = false;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        getVoiceList(loadMore: true);
      }
    });
    getVoiceList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3c),
      body:
      ListView.builder(
          itemCount: roomList.length,
          controller: _scrollController,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder:(context,index){
            return VoiceList(voiceRoomEntity: roomList[index],);
          }
      ),
    );
  }

  Future<void> getVoiceList({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = RoomRequest();
      request
          .add('page', currentIndex)
          .add('classify_id', widget.categoryName)
          .add('type', 2)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
        new List<Map<String, dynamic>>.from(result['data']);
        List<VoiceRoomEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(VoiceRoomEntity.fromJson(listMap[i]));
        }
        setState(() {
          if (loadMore) {
            if (list.isNotEmpty) {
              //合成一个新数组
              roomList = [...roomList, ...list];
              pageIndex++;
            }
          } else {
            roomList = list;
          }
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          _loading = false;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }
}
